package api

import (
	"context"
	"fmt"
	"net/http"
	"strings"
	"time"

	"shop_api/user_web/forms"
	"shop_api/user_web/global"

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"golang.org/x/exp/rand"
)

func GenerateSmsCode(width int) string {
	numberic := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numberic)
	rand.Seed(uint64(time.Now().UnixNano()))

	var sb strings.Builder
	for i := 0; i < width; i++ {
		_, _ = fmt.Fprintf(&sb, "%d", numberic[rand.Intn(r)])
	}
	return sb.String()
}

func SendSms(c *gin.Context) {
	sendSmsForm := forms.SendSmsForm{}
	if err := c.ShouldBindJSON(&sendSmsForm); err != nil {
		HandleValidatorError(c, err)
		return
	}

	// 短信先不发的
	smsCode := GenerateSmsCode(6)
	rdb := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
	})
	rdb.Set(context.Background(), sendSmsForm.Mobile, smsCode, time.Duration(global.ServerConfig.RedisInfo.Expire)*time.Second)
	c.JSON(http.StatusOK, gin.H{
		"msg": "发送成功",
	})
}
